import React from 'react';
import { Menu } from 'antd';
import type { MenuProps } from 'antd/es/menu';
import { SvgIcon } from '@/components/icon';

export interface MenuItem {
  key: string;
  label: React.ReactNode;
  icon?: string;
  className?: string;
  disabled?: boolean;
  children?: MenuItem[];
  type?: 'group' | 'divider';
}

export interface CustomMenuProps {
  mode?: 'vertical' | 'horizontal' | 'inline';
  theme?: 'light' | 'dark';
  items: MenuItem[];
  className?: string;
  style?: React.CSSProperties;
  onClick?: MenuProps['onClick'];
  selectedKeys?: string[];
}
export const CustomMenu: React.FC<CustomMenuProps> = ({
  mode = 'inline',
  theme = 'light',
  items,
  className = '',
  selectedKeys,
  style,
  onClick,
  ...props
}) => {
  const convertItems = (items: MenuItem[], level = 0): MenuProps['items'] => {
    return items.map((item) => {
      if (item.type === 'divider') {
        return { type: 'divider' };
      }
      const indentClass = level > 0 ? 'pl-8' : ''; // 二级及以上菜单添加缩进
      const isGroup = item.children && item.children.length > 0;
      const itemClassName = [
        item.className || '',
        indentClass,
        level > 0 ? 'text-sm' : 'font-medium', // 二级菜单字体稍小
        isGroup ? 'group-item' : '',
      ]
        .filter(Boolean)
        .join(' ');
      return {
        key: item.key,
        label: item.label,
        icon: <SvgIcon icon={item.icon as string} size={20} />,
        disabled: item.disabled,
        className: itemClassName,
        children: item.children ? convertItems(item.children, level + 1) : undefined,
      };
    });
  };

  const menuItems = convertItems(items);

  return (
    <Menu
      mode={mode}
      theme={theme}
      items={menuItems}
      selectedKeys={selectedKeys}
      className={`custom-menu rounded-lg border-0 !text-sm  ${className}`}
      style={style}
      onClick={onClick}
      {...props}
    />
  );
};
